package com.nciae.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.nciae.po.User;
import com.nciae.dao.UserMapper;
import com.nciae.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Guoliyu
 * @since 2022-03-30
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Override
    public User findUserById(Long id) {
        return baseMapper.selectById(id);
    }

    @Override
    public User findUserByName(String username) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.like("username", username);
        return baseMapper.selectOne(wrapper);
    }

    /**
     * 登录
     * @param username：用户名
     * @param password：密码
     * @return
     */
    @Override
    public User login(String username, String password) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("username", username);
        wrapper.eq("password", password);
        User user = baseMapper.selectOne(wrapper);
        if (Objects.isNull(user)) {
            throw new RuntimeException();
        }
        return user;
    }

    @Override
    public void add(User user) {
        baseMapper.insert(user);
    }

    @Override
    public void update(User user) {
        baseMapper.updateById(user);
    }

    @Override
    public void delete(Long id) {
        baseMapper.deleteById(id);
    }

    @Override
    public byte[] uploadAvator(Long userId, MultipartFile file) {
        try {
            return file.getBytes();
        } catch (IOException e) {
            return null;
        }
    }

    @Override
    public List<User> findUserByUsername(String username) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.like("username", username);
        return baseMapper.selectList(wrapper);
    }
}
